package service

import (
	"errors"
	"fmt"
	"ginchat/models/mysqlModel"
	"ginchat/models/requstModel"
	"ginchat/sql/userSql"
	"ginchat/utils/md5"
	"ginchat/utils/redisInit"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"gorm.io/gorm"
	"math/rand"
	"time"
)

// 获取所有用户
func GetUserList() ([]mysqlModel.UserBasic,error){
	data,err := userSql.GetUserList()
	if err != nil{
		return nil,err
	}
	return  data,nil
}

//创建用户
func CreateUser(requstMode requstModel.CreateUserRequst) (mysqlModel.UserBasic,error){
	//验证密码是否一致
	if requstMode.Password != requstMode.RePassword {
		err := errors.New("密码不一致！")
		return mysqlModel.UserBasic{},err
	}
	if requstMode.Name == ""{
		err := errors.New("姓名不能为空！")
		return mysqlModel.UserBasic{},err
	}

	user := mysqlModel.UserBasic{}
	var err error

	//用户名不能重复
	_,err = userSql.FindUserByName(requstMode.Name)
	if err != gorm.ErrRecordNotFound{
		er := errors.New("用户已注册！")
		return user,er
	}

	//邮箱不能重复
	_,err = userSql.FindUserByEmail(requstMode.Email)
	if err != gorm.ErrRecordNotFound{
		er := errors.New("邮箱已注册！")
		return user,er
	}

	//手机号不能重复
	_,err = userSql.FindUserByPhone(requstMode.Phone)
	if err != gorm.ErrRecordNotFound{
		er := errors.New("手机号已注册！")
		return user,er
	}

	//加密密码
	salt := fmt.Sprintf("%06d",rand.Int())
	requstMode.Password = md5.MakePassword(requstMode.Password,salt)

	if user,err = userSql.CreateUser(requstMode,salt);err != nil {
		return user,err
	}
	return user,nil
}

//删除用户
func DeleteUser(id int) error{
	if err := userSql.DeleteUser(id);err != nil{
		return err
	}
	return nil
}

//修改用户
func UpdateUser(requstMode requstModel.UpdateUserRequst) error {
	if err := userSql.UpdateUser(requstMode );err != nil{
		return err
	}
	return nil
}

//用户登录
func UserLog(name,password string) (mysqlModel.UserBasic,error){
	user,err := userSql.FindUserByNameAndPassword(name,password)
	if err != nil{
		if err == gorm.ErrRecordNotFound{
			err := errors.New("用户不存在")
			return user,err
		}
		return user,err
	}

	if !md5.ValidPassword(password,user.Salt,user.Password){
		err := errors.New("密码错误")
		return user,err
	}

	//token的加入
	str := fmt.Sprintf("%d",time.Now().Unix())
	temp := md5.MD5Encode(str)
	if err := userSql.NewToken(&user,temp);err != nil{
		return mysqlModel.UserBasic{},err
	}
	return user,nil
}


//处理消息
func MsgHandler(wsConn *websocket.Conn,c *gin.Context){
	for {
		msg,err := redisInit.FSubscribe(c,redisInit.PublishKey)
		if err != nil{
			fmt.Println("redisInit.Subscribe failed:",err)
			return
		}
		tm := time.Now().Format("2006-01-02 15:04:05")
		m := fmt.Sprintf("[ws][%s]:%s",tm,msg)
		if err := wsConn.WriteMessage(1,[]byte(m));err != nil{
			fmt.Println("wsConn.WriteMessage failed:",err)
			return
		}
	}
}

//查找好友列表
func SearchFriend(userId uint)[]mysqlModel.UserBasic{
	return userSql.SearchFriend(userId)
}

func AddFriend(userId uint,targetId uint) (int,string){
	return userSql.AddFriend(userId,targetId)
}

func CreateCommunity(community mysqlModel.Community)(int,string){
	return userSql.CreateCommunity(community)
}

func LoadCommunity(owner_id uint) (error,[]mysqlModel.Community){
	return userSql.LoadCommunity(owner_id)
}

func JoinGroup(userId uint,comId uint) (int,string){
	contact := mysqlModel.Contact{
		OwnerId: userId,
		TargetId: comId,
		Type: 2,
	}
	return userSql.JoinGroup(contact)
}

